package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.blue.ui.DynamicWaveFormView;
import org.example.result.FeaResult;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;


public class DuizhiActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener,DataProcessorManagerRight.DataUpdateListener{
    private static final String TAG = "DuizhiActivity";
    private String deviceId;
    private BluetoothService bluetoothService;
    private boolean isBound=false;
    private Button btn;
    private Boolean startFlag=false;
    private DynamicWaveFormView waveformViewX;
    private DynamicWaveFormView waveformViewY;
    private DynamicWaveFormView waveformViewZ;
    private LinearLayout groupLayout;
    private ImageView imageView;
    private TextView shuomingText;
    private DataProcessorManager processorManager;
    private DataProcessorManagerRight processorManagerRight;
    private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private LinkedBlockingDeque<byte[]> dataQueue2 = new LinkedBlockingDeque<>();
//    private LinkedBlockingQueue<byte[]> dataQueue = new LinkedBlockingQueue<>(5000);
//    private LinkedBlockingQueue<byte[]> dataQueue2 = new LinkedBlockingQueue<>(5000);
    private Integer conDeviceNum=1;
    private String deviceMacLeft;
    private String deviceMacRight;
    private Boolean isJiaozhun1=false;
    private Boolean isJiaozhun2=false;
    private Integer handDir=0;
    private LinearLayout groupSpinner;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
    private Button reportBtn;
    private Handler handler = new Handler();
    private FrameLayout loadingLayout;
    private SharedPreferences sp;
    private Boolean isLeftDeviceReceived=false;
    private Boolean isRightDeviceReceived=false;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
//            if(conDeviceNum==1){
//                if(handDir==1) {
//                    dataQueue  = bluetoothService.getDataQueueLeft();
//                    processorManager = DataProcessorManager.getInstance(dataQueue);
//                }else{
//                    dataQueue2  = bluetoothService.getDataQueueRight();
//                    processorManager = DataProcessorManager.getInstance(dataQueue2);
//                }
//            }
//            else{
//                dataQueue  = bluetoothService.getDataQueueLeft();
//                dataQueue2  = bluetoothService.getDataQueueRight();
//                processorManager = DataProcessorManager.getInstance(dataQueue);
//                processorManagerRight=DataProcessorManagerRight.getInstance(dataQueue2);
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_duizhi);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("对指测试");

        sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        handDir = sp.getInt("handDirection",0);
        isLeftDeviceReceived=sp.getBoolean("isLeftDeviceReceived",false);
        isRightDeviceReceived=sp.getBoolean("isRightDeviceReceived",false);
        if(conDeviceNum==1) {

            if(handDir==1){
                if(isLeftDeviceReceived==false){
                    Toast.makeText(DuizhiActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
            }else{
                if(isRightDeviceReceived==false){
                    Toast.makeText(DuizhiActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
            }
        }
        if(conDeviceNum==2){
            if(isLeftDeviceReceived==false){
                Toast.makeText(DuizhiActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }else if(isRightDeviceReceived==false){
                Toast.makeText(DuizhiActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
        }

        imageView=findViewById(R.id.imageView);
        shuomingText=findViewById(R.id.shuoming);
        groupLayout=findViewById(R.id.group_container);
        groupSpinner=findViewById(R.id.group_spinner);
        loadingLayout  = findViewById(R.id.loadingLayout);
        loadingLayout.setVisibility(View.GONE);
        waveformViewX = findViewById(R.id.waveformView1);
        waveformViewY = findViewById(R.id.waveformView2);
        waveformViewZ = findViewById(R.id.waveformView3);
        waveformViewX.setYtitle("Z轴欧拉角(deg)");
        waveformViewX.setYRange(-180,180);
        waveformViewY.setYtitle("Y轴欧拉角(deg)");
        waveformViewY.setYRange(-180,180);
        waveformViewZ.setYtitle("X轴欧拉角(deg)");
        waveformViewZ.setYRange(-180,180);
        if(startFlag==false){
            groupLayout.setVisibility(View.GONE);
        }else{
            groupLayout.setVisibility(View.VISIBLE);
        }

        btn = findViewById(R.id.startBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isJiaozhun1=false;
                isJiaozhun2=false;
                SharedPreferences.Editor editor=sp.edit();
                editor.putBoolean("isDuizhiStart", true);
                editor.remove("isJiaozhun1");
                editor.remove("isJiaozhun2");
                editor.apply();
                if(conDeviceNum==1) {
                    if(handDir==1){
                        if(isLeftDeviceReceived==false){
                            Toast.makeText(DuizhiActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                            return;
                        }
                            dataQueue  = bluetoothService.getDataQueueLeft();
                            processorManager = DataProcessorManager.getInstance(dataQueue);
                    }
                    if(handDir==2){
                        if (isRightDeviceReceived == false) {
                            Toast.makeText(DuizhiActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        dataQueue2  = bluetoothService.getDataQueueRight();
                        processorManager = DataProcessorManager.getInstance(dataQueue2);
                    }
                        groupLayout.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        shuomingText.setVisibility(View.GONE);
                        btn.setVisibility(View.GONE);
                        reportBtn.setVisibility(View.GONE);
                        groupSpinner.setVisibility(View.GONE);
                        processorManager.setDeviceMac(deviceId.replace(":", ""));
                        processorManager.temp = handDir;
                        processorManager.setDataUpdateListener(DuizhiActivity.this);
                        processorManager.startProcessing();
                        processorManager.setProcessingFunction(ProcessingFunction.Blank);
                        processorManager.setzero();
                        processorManager.setProcessingFunction(ProcessingFunction.Duizhiout);
                        Toast.makeText(DuizhiActivity.this, "开始测试", Toast.LENGTH_SHORT).show();

                }else {
                    if(isLeftDeviceReceived==false){
                        Toast.makeText(DuizhiActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                    }else if(isRightDeviceReceived==false){
                        Toast.makeText(DuizhiActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                    }else {
                        groupLayout.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        shuomingText.setVisibility(View.GONE);
                        btn.setVisibility(View.GONE);
                        reportBtn.setVisibility(View.GONE);
                        groupSpinner.setVisibility(View.VISIBLE);
                        dataQueue  = bluetoothService.getDataQueueLeft();
                        processorManager = DataProcessorManager.getInstance(dataQueue);
                        processorManager.setDataUpdateListener(DuizhiActivity.this);
                        processorManager.startProcessing();
                        processorManager.setDeviceMac(deviceMacLeft.replace(":", ""));
                        processorManager.temp = 1;
                        processorManager.setProcessingFunction(ProcessingFunction.Blank);
                        processorManager.setzero();
                        processorManager.setProcessingFunction(ProcessingFunction.Duizhiout);

                        dataQueue2  = bluetoothService.getDataQueueRight();
                        processorManagerRight=DataProcessorManagerRight.getInstance(dataQueue2);
                        processorManagerRight.setDataUpdateListener(DuizhiActivity.this);
                        processorManagerRight.startProcessing();
                        processorManagerRight.setDeviceMac(deviceMacRight.replace(":", ""));
                        processorManagerRight.temp = 2;
                        processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
                        processorManagerRight.setzero();
                        processorManagerRight.setProcessingFunction(ProcessingFunction.Duizhiout);

                        Toast.makeText(DuizhiActivity.this, "开始测试", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        reportBtn=findViewById(R.id.reportBtn);
        reportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 Runnable checkRunnable = new Runnable() {
                    @Override
                    public void run() {
                        Boolean isDuizhiStart = sp.getBoolean("isDuizhiStart",false);
                        System.out.println("DuichiActivity----------------isDuizhiStart:" + isDuizhiStart);

                        if(isDuizhiStart==false){
                            Toast.makeText(DuizhiActivity.this,"请先开始测试",Toast.LENGTH_SHORT).show();
                        }else {
                            if (conDeviceNum == 1) {
                                isJiaozhun1 = sp.getBoolean("isJiaozhun1", false);
                                System.out.println("DuichiActivity----------------isJiaozhun1:" + isJiaozhun1);
                                if (isJiaozhun1) {
                                    // 变量变为true，执行操作
                                    loadingLayout.setVisibility(View.GONE);
                                    Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
                                    startActivity(intent);
                                } else {
                                    // 继续检查，但要有间隔
                                    loadingLayout.setVisibility(View.VISIBLE);
                                    handler.postDelayed(this, 100); // 每100ms检查一次
                                }
                            } else {
                                isJiaozhun1 = sp.getBoolean("isJiaozhun1", false);
                                System.out.println("DuichiActivity----------------isJiaozhun1:" + isJiaozhun1);
                                isJiaozhun2 = sp.getBoolean("isJiaozhun2", false);
                                System.out.println("DuichiActivity----------------isJiaozhun2:" + isJiaozhun2);
                                if (isJiaozhun1 == true && isJiaozhun2 == true) {
                                    loadingLayout.setVisibility(View.GONE);
                                    Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
                                    startActivity(intent);
                                } else {
                                    loadingLayout.setVisibility(View.VISIBLE);
                                    handler.postDelayed(this, 100);
                                }
                            }
                        }
                    }
                };
                handler.postDelayed(checkRunnable, 100);
//                isJiaozhun1 = sp.getBoolean("isJiaozhun1",false);
//                isJiaozhun2 = sp.getBoolean("isJiaozhun2",false);
//                if(conDeviceNum==1) {
//                    if (isJiaozhun1 == true) {
//                        Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
//                        startActivity(intent);
//                    } else {
//                        Toast.makeText(DuizhiActivity.this, "请先完成对指测试", Toast.LENGTH_SHORT).show();
//                    }
//                }else{
//                    if (isJiaozhun1==true && isJiaozhun2==true) {
//                        Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
//                        startActivity(intent);
//                    }else{
//                        Toast.makeText(DuizhiActivity.this, "请先完成对指测试", Toast.LENGTH_SHORT).show();
//                    }
//
//                }
            }

        });
        spinner = findViewById(R.id.modeSpinner);
        String[] options = {"左手", "右手"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
// 监听选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX.clearDataPoints();
                    waveformViewY.clearDataPoints();
                    waveformViewZ.clearDataPoints();
                }
                selectedSensorNum=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getAngle();
        String flag = data.getFlag();
        System.out.println("duizhi-Flag-l:"+flag);
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
            return;
        }
        if(flag.equals("duizhiout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
             System.out.println("dataArr: " + dataArr[0]+" "+dataArr[1]+" "+dataArr[2]);
            String da1 = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
            String da2 = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
            String da3 = dataArr[0].length()>10?dataArr[0].substring(0,8):dataArr[0];
            if(selectedSensorNum==0) {
                waveformViewX.addDataPoint(Float.parseFloat(da1));
                waveformViewY.addDataPoint(Float.parseFloat(da2));
                waveformViewZ.addDataPoint(Float.parseFloat(da3));
            }
        }
        if(flag.equals("duizhiResult")){
           // Toast.makeText(DuizhiActivity.this,"测试完成，正在计算结果",Toast.LENGTH_SHORT).show();
            isJiaozhun1=true;
            processorManager.stopProcessing();
            FeaResult duizhiRes = data.getFeaResult();
            System.out.println("duizhi"+" "+duizhiRes.predictLabel+" "+duizhiRes.predictScore);
            SharedPreferences.Editor editor=sp.edit();
            editor.putBoolean("isDuizhi", true);
            editor.putBoolean("isJiaozhun1", true);

            editor.putInt("predictLabel",duizhiRes.predictLabel);
            editor.putInt("predictScore",duizhiRes.predictScore);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < duizhiRes.displayFea.length; i++) {
                sb.append(duizhiRes.displayFea[i]);
                if (i < duizhiRes.displayFea.length - 1) sb.append(",");
            }
            editor.putString("displayFea", sb.toString());
            editor.apply();

            if(conDeviceNum==1) {
//                    Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
//                    startActivity(intent);
              //  finish();
                Toast.makeText(this,"测试完成",Toast.LENGTH_SHORT).show();
                groupLayout.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                shuomingText.setVisibility(View.VISIBLE);
                btn.setVisibility(View.VISIBLE);
                reportBtn.setVisibility(View.VISIBLE);
                groupSpinner.setVisibility(View.GONE);
            }
            if(conDeviceNum==2){
                if (isJiaozhun1==true && isJiaozhun2==true) {
                    Toast.makeText(this,"测试完成",Toast.LENGTH_SHORT).show();
//                    Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
//                    startActivity(intent);
                   // finish();
                    groupLayout.setVisibility(View.GONE);
                    imageView.setVisibility(View.VISIBLE);
                    shuomingText.setVisibility(View.VISIBLE);
                    btn.setVisibility(View.VISIBLE);
                    reportBtn.setVisibility(View.VISIBLE);
                    groupSpinner.setVisibility(View.GONE);
                }
            }

        }
    }
    @Override
    public void onDataProcessedRight(ProcessedData data){
        String processedValue = data.getAngle();
        String flag = data.getFlag();
        System.out.println("duizhi-Flag-r:"+flag);
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
            return;
        }
        if(flag.equals("duizhiout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
            System.out.println("dataArr: " + dataArr[0]+" "+dataArr[1]+" "+dataArr[2]);
            String da1 = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
            String da2 = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
            String da3 = dataArr[0].length()>10?dataArr[0].substring(0,8):dataArr[0];
            if(selectedSensorNum==1) {
                waveformViewX.addDataPoint(Float.parseFloat(da1));
                waveformViewY.addDataPoint(Float.parseFloat(da2));
                waveformViewZ.addDataPoint(Float.parseFloat(da3));
            }
        }
        if(flag.equals("duizhiResult")){
            // Toast.makeText(DuizhiActivity.this,"测试完成，正在计算结果",Toast.LENGTH_SHORT).show();
            isJiaozhun2=true;
            processorManagerRight.stopProcessing();
            FeaResult duizhiRes = data.getFeaResult();
            System.out.println("duizhi"+" "+duizhiRes.predictLabel+" "+duizhiRes.predictScore);
            SharedPreferences.Editor editor=sp.edit();
            editor.putBoolean("isDuizhi", true);
            editor.putBoolean("isJiaozhun2", true);
            editor.putInt("predictLabelR",duizhiRes.predictLabel);
            editor.putInt("predictScoreR",duizhiRes.predictScore);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < duizhiRes.displayFea.length; i++) {
                sb.append(duizhiRes.displayFea[i]);
                if (i < duizhiRes.displayFea.length - 1) sb.append(",");
            }
            editor.putString("displayFeaR", sb.toString());
            editor.apply();
            if (isJiaozhun1==true && isJiaozhun2==true) {
                Toast.makeText(this,"测试完成",Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(DuizhiActivity.this, DuizhiResActivity.class);
//                startActivity(intent);
//                finish();
                groupLayout.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                shuomingText.setVisibility(View.VISIBLE);
                btn.setVisibility(View.VISIBLE);
                reportBtn.setVisibility(View.VISIBLE);
                groupSpinner.setVisibility(View.GONE);
            }

        }
    }

    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if(conDeviceNum==1) {
//            processorManager.setProcessingFunction(ProcessingFunction.Blank);
//        }else {
//            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if(conDeviceNum==1) {
//            processorManager.setProcessingFunction(ProcessingFunction.Blank);
//        }else {
//            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
//        }
    }
}